import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";

import {
  Database,
  Search,
  Filter,
  Download,
  Eye,
  Video,
  ExternalLink,
  Calendar,
  TrendingUp,
  Heart,
  MessageCircle,
  RefreshCw,
} from "lucide-react";

import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { useNavigate } from "react-router-dom";

import { useToast, showError } from "@/hooks/use-toast";

import { getAnalysisList, reAnalysis } from "@/api/VideoAnalysis";

const VideoLibrary = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [platformFilter, setPlatformFilter] = useState("all");
  const [minViews, setMinViews] = useState("");
  const [maxViews, setMaxViews] = useState("");
  const [minGMV, setMinGMV] = useState("");
  const [maxGMV, setMaxGMV] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [publishStartDate, setPublishStartDate] = useState("");
  const [publishEndDate, setPublishEndDate] = useState("");
  const [selectedVideos, setSelectedVideos] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  const [dataList, setDataList] = useState([]);
  const [pageAction, setPageAction] = useState({
    currentPage: 1,
    pageSize: 10,
    totalPages: 0,
    total: 0,
  });

  const { toast } = useToast();

  const getDataList = async (
    pageNum: number = pageAction.currentPage,
    pageSize: number = pageAction.pageSize
  ) => {
    setLoading(true);
    const data = await getAnalysisList({
      pageSize,
      pageNum,
    });

    const { rows, total, code } = data;
    if (code == 200) {
      setDataList(rows);
      setLoading(false);
      setPageAction((prev) => ({
        ...prev,
        totalPages: Math.ceil(total / pageAction.pageSize),
        total,
        currentPage: pageNum,
      }));
    }
  };

  const handlePageChange = async (
    currentPage: number = pageAction.currentPage
  ) => {
    // if (currentPage == pageAction.currentPage) return;
    await getDataList(currentPage);
  };
  const navigate = useNavigate();

  const handleViewScript = (videoId: string) => {
    navigate(`/script/${videoId}`);
  };

  const handleDownloadScript = (videoId: string) => {
    // 模拟下载功能
    console.log(`下载脚本: ${videoId}`);
  };

  const handleDownloadVideo = (videoId: string) => {
    // 模拟下载功能
    console.log(`下载视频: ${videoId}`);
  };

  const handleExport = () => {
    // 模拟导出功能
    console.log("导出视频库数据");
  };

  const handleReparse = async (videoId: string) => {
    // 模拟重新解析功能
    const data = await reAnalysis(videoId);
    if (data?.code == 200) {
      toast({
        title: "提交成功",
        description: `提交成功，等到解析中`,
      });
      await getDataList();
    }
  };

  const handleBatchReparse = () => {
    // 模拟批量重新解析功能
    console.log(`批量重新解析视频: ${selectedVideos.join(", ")}`);
    setSelectedVideos([]);
  };

  const handleSelectVideo = (videoId: string, checked: boolean) => {
    if (checked) {
      setSelectedVideos((prev) => [...prev, videoId]);
    } else {
      setSelectedVideos((prev) => prev.filter((id) => id !== videoId));
    }
  };

  const handleSelectAll = (checked: boolean) => {
    // if (checked) {
    //   setSelectedVideos(filteredVideos.map((video) => video.id));
    // } else {
    //   setSelectedVideos([]);
    // }
  };

  const getStatusBadge = (status: string, errmsg: string) => {
    const statusConfig = {
      NONE: {
        variant: "none" as const,
        color: "text-white",
        txt: "未解析",
      },
      START: {
        variant: "secondary" as const,
        color: "text-black",
        txt: "排队中",
      },
      DOWNLOADING: {
        variant: "default" as const,
        color: "text-white",
        txt: "下载中",
      },
      DOWNLOAD: {
        variant: "default" as const,
        color: "text-white",
        txt: "初始化",
      },
      EXTRACT: {
        variant: "default" as const,
        color: "text-white",
        txt: "AI解析中",
      },
      ERROR: {
        variant: "destructive" as const,
        color: "text-white",
        txt: "错误",
      },
      END: {
        variant: "success" as const,
        color: "text-white",
        txt: "完成",
      },
    };

    const config =
      statusConfig[status as keyof typeof statusConfig] || statusConfig["NONE"];
    return (
      <Badge variant={config.variant} className={config.color}>
        {status == "ERROR" ? errmsg : config.txt}
      </Badge>
    );
  };

  const formatNumber = (num: number = 0) => {
    if (!num) num = 0;
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + "M";
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + "K";
    }
    return num.toString();
  };

  useEffect(() => {
    getDataList();
  }, []);

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold mb-3 bg-[var(--gradient-hero)] bg-clip-text text-transparent">
            视频库
          </h1>
          <p className="text-muted-foreground text-lg">
            管理和分析已收集的视频内容
          </p>
        </div>
      </div>

      {/* 筛选面板 */}
      <Card className="mb-6 shadow-[var(--shadow-card)] border-0">
        <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-5 w-5 text-primary" />
            筛选条件
          </CardTitle>
          <CardDescription>通过多种条件快速筛选视频内容</CardDescription>
        </CardHeader>
        <CardContent className="pt-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
            <div className="space-y-2">
              <Label htmlFor="search">搜索链接/内容</Label>
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="搜索视频链接或内容"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="platform">视频平台</Label>
              <Select value={platformFilter} onValueChange={setPlatformFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="选择平台" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部平台</SelectItem>
                  <SelectItem value="TikTok">TikTok</SelectItem>
                  {/* <SelectItem value="Instagram">Instagram</SelectItem>
                  <SelectItem value="Youtube">YouTube</SelectItem> */}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>收集日期</Label>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  placeholder="开始日期"
                />
                <Input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  placeholder="结束日期"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>播放量范围</Label>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  type="number"
                  placeholder="最小值"
                  value={minViews}
                  onChange={(e) => setMinViews(e.target.value)}
                />
                <Input
                  type="number"
                  placeholder="最大值"
                  value={maxViews}
                  onChange={(e) => setMaxViews(e.target.value)}
                />
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>发布日期</Label>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  type="date"
                  value={publishStartDate}
                  onChange={(e) => setPublishStartDate(e.target.value)}
                  placeholder="开始日期"
                />
                <Input
                  type="date"
                  value={publishEndDate}
                  onChange={(e) => setPublishEndDate(e.target.value)}
                  placeholder="结束日期"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>GMV 范围</Label>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  type="number"
                  placeholder="最小GMV"
                  value={minGMV}
                  onChange={(e) => setMinGMV(e.target.value)}
                />
                <Input
                  type="number"
                  placeholder="最大GMV"
                  value={maxGMV}
                  onChange={(e) => setMaxGMV(e.target.value)}
                />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <Card className="border-0 shadow-[var(--shadow-card)]">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总视频数</p>
                <p className="text-2xl font-bold text-primary">
                  {pageAction.total}
                </p>
              </div>
              <Database className="h-8 w-8 text-primary opacity-60" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-[var(--shadow-card)]">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总播放量</p>
                <p className="text-2xl font-bold text-primary">{0}</p>
              </div>
              <TrendingUp className="h-8 w-8 text-primary opacity-60" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-[var(--shadow-card)]">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总GMV</p>
                <p className="text-2xl font-bold text-primary">¥{0}</p>
              </div>
              <TrendingUp className="h-8 w-8 text-success opacity-60" />
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-[var(--shadow-card)]">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">平均互动率</p>
                <p className="text-2xl font-bold text-primary">8.5%</p>
              </div>
              <Heart className="h-8 w-8 text-primary opacity-60" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 视频列表 */}
      <Card className="shadow-[var(--shadow-card)] border-0">
        <CardHeader className="bg-[var(--gradient-secondary)] rounded-t-lg">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Video className="h-5 w-5 text-primary" />
                视频列表
              </CardTitle>
              <CardDescription>
                找到 {pageAction.total} 个符合条件的视频
              </CardDescription>
              <Button
                variant="outline"
                onClick={() => handlePageChange()}
                disabled={loading}
                className="shadow-[var(--shadow-button)]"
              >
                <RefreshCw
                  className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`}
                />
                刷新数据
              </Button>
            </div>
            <div className="flex gap-3">
              {/* {selectedVideos.length > 0 && (
                <Button
                  variant="outline"
                  onClick={handleBatchReparse}
                  className="shadow-[var(--shadow-button)]"
                >
                  <RefreshCw className="h-4 w-4 mr-2" />
                  批量重新解析 ({selectedVideos.length})
                </Button>
              )} */}
              <Button
                variant="hero"
                onClick={handleExport}
                className="shadow-[var(--shadow-button)]"
              >
                <Download className="h-4 w-4 mr-2" />
                导出数据
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="border-b">
                  <TableHead className="w-12">
                    <Checkbox onCheckedChange={handleSelectAll} />
                  </TableHead>
                  <TableHead className="w-32">视频ID</TableHead>
                  <TableHead className="w-24">平台</TableHead>
                  <TableHead className="w-96">视频链接</TableHead>
                  <TableHead className="w-48">收集日期</TableHead>
                  <TableHead className="w-48">发布日期</TableHead>
                  <TableHead className="w-24">播放量</TableHead>
                  <TableHead className="w-24">GMV</TableHead>
                  <TableHead className="w-32">互动数据</TableHead>
                  <TableHead className="w-48">状态</TableHead>
                  <TableHead className="w-48">脚本摘要</TableHead>
                  <TableHead className="w-32">产品/品牌</TableHead>
                  <TableHead className="w-48">评论区互动分析</TableHead>
                  <TableHead className="w-48">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {dataList.map((video) => (
                  <TableRow key={video.id} className="hover:bg-muted/50">
                    <TableCell>
                      <Checkbox
                        checked={selectedVideos.includes(video.id)}
                        onCheckedChange={(checked) =>
                          handleSelectVideo(video.id, checked as boolean)
                        }
                      />
                    </TableCell>
                    <TableCell className="font-mono text-xs">
                      {video.videoNo}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{video.postPlatform}</Badge>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-48">
                        <a
                          href={video.videoLink}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="break-all text-primary hover:text-primary/80 text-xs underline flex items-center gap-1"
                        >
                          <ExternalLink className="h-3 w-3" />
                          {video.videoLink}
                        </a>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1 text-sm">
                        <Calendar className="h-3 w-3" />
                        {video.postLastUpdateData}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1 text-sm">
                        <Calendar className="h-3 w-3" />
                        {video.workTime}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <TrendingUp className="h-3 w-3 text-primary" />
                        <span className="font-semibold">
                          {formatNumber(video.videoViews)}
                        </span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <span className="font-semibold text-success">
                        ¥{formatNumber(video.gmvUsd)}
                      </span>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-1 text-xs">
                        <div className="flex items-center gap-1">
                          <Heart className="h-3 w-3 text-red-500" />
                          {formatNumber(video.likes)}
                        </div>
                        <div className="flex items-center gap-1">
                          <MessageCircle className="h-3 w-3 text-blue-500" />
                          {formatNumber(video.comments)}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      {getStatusBadge(video.status, video.errmsg)}
                    </TableCell>
                    <TableCell>
                      <div className="max-w-48">
                        <p className="text-sm font-medium mb-1">
                          {video.summary}
                        </p>
                        <p className="text-xs text-muted-foreground truncate">
                          {video.originalScript}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <Badge variant="outline" className="text-xs">
                          {video.products}
                        </Badge>
                        <div className="text-xs text-muted-foreground">
                          {video.brand}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-48">
                        <p className="text-xs text-muted-foreground">
                          {video.engagement}
                        </p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-2">
                        {video.status == "END" && (
                          <>
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleViewScript(video.id)}
                              >
                                <Eye className="h-3 w-3 mr-1" />
                                查看详情
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleReparse(video.id)}
                              >
                                <RefreshCw className="h-3 w-3 mr-1" />
                                重新解析
                              </Button>
                            </div>
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleDownloadScript(video.id)}
                              >
                                <Download className="h-3 w-3 mr-1" />
                                脚本
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => handleDownloadVideo(video.id)}
                              >
                                <Video className="h-3 w-3 mr-1" />
                                视频
                              </Button>
                            </div>
                          </>
                        )}
                        {video.status == "ERROR" && (
                          <>
                            <div className="flex gap-1">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleReparse(video.id)}
                              >
                                <RefreshCw className="h-3 w-3 mr-1" />
                                重新解析
                              </Button>
                            </div>
                          </>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {/* Loading Overlay */}
          {loading && (
            <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-10">
              <div className="flex flex-col items-center gap-4">
                <RefreshCw className="h-8 w-8 animate-spin text-primary" />
                <p className="text-sm text-muted-foreground">正在加载数据...</p>
              </div>
            </div>
          )}

          {/* Loading Overlay */}
          {loading && (
            <div className="absolute inset-0 bg-background/80 backdrop-blur-sm flex items-center justify-center z-10">
              <div className="flex flex-col items-center gap-4">
                <RefreshCw className="h-8 w-8 animate-spin text-primary" />
                <p className="text-sm text-muted-foreground">正在加载数据...</p>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      {/* 分页器 */}
      {pageAction.totalPages > 1 && (
        <div className="flex justify-center mt-6">
          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    if (pageAction.currentPage > 1)
                      handlePageChange(pageAction.currentPage - 1);
                  }}
                  className={
                    pageAction.currentPage <= 1
                      ? "pointer-events-none opacity-50"
                      : ""
                  }
                />
              </PaginationItem>

              {Array.from(
                { length: pageAction.totalPages },
                (_, i) => i + 1
              ).map((page) => {
                if (
                  page === 1 ||
                  page === pageAction.totalPages ||
                  (page >= pageAction.currentPage - 1 &&
                    page <= pageAction.currentPage + 1)
                ) {
                  return (
                    <PaginationItem key={page}>
                      <PaginationLink
                        href="#"
                        onClick={(e) => {
                          e.preventDefault();
                          handlePageChange(page);
                        }}
                        isActive={pageAction.currentPage === page}
                      >
                        {page}
                      </PaginationLink>
                    </PaginationItem>
                  );
                } else if (
                  page === pageAction.currentPage - 2 ||
                  page === pageAction.currentPage + 2
                ) {
                  return (
                    <PaginationItem key={page}>
                      <PaginationEllipsis />
                    </PaginationItem>
                  );
                }
                return null;
              })}

              <PaginationItem>
                <PaginationNext
                  href="#"
                  onClick={(e) => {
                    e.preventDefault();
                    if (pageAction.currentPage < pageAction.totalPages)
                      handlePageChange(pageAction.currentPage + 1);
                  }}
                  className={
                    pageAction.currentPage >= pageAction.totalPages
                      ? "pointer-events-none opacity-50"
                      : ""
                  }
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      )}
    </div>
  );
};

export default VideoLibrary;
